<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="月份" prop="monthCode">
            <el-input v-model="queryParams.monthCode" placeholder="请输入月份" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="info" @click="back()" icon="Back">返回</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['credit:monthRecord:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['credit:monthRecord:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['credit:monthRecord:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" icon="Download" @click="handleExport" v-hasPermi="['credit:monthRecord:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="billMonthRecordList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="月份" align="center" prop="monthCode" />
        <el-table-column label="刷卡账单生成状态" align="center" prop="posState">
          <template #default="scope">
            <el-tag type="warning" v-if="scope.row.posState == 0">未生成</el-tag>
            <el-tag type="success" v-else-if="scope.row.posState == 1">生成成功</el-tag>
            <el-tooltip content="点击重新生成" placement="top" v-else-if="scope.row.posState == 2">
              <el-button type="danger" size="small">生成失败</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="扫码账单生成状态" align="center" prop="qrState">
          <template #default="scope">
            <el-tag type="warning" v-if="scope.row.qrState == 0">未生成</el-tag>
            <el-tag type="success" v-else-if="scope.row.qrState == 1">生成成功</el-tag>
            <el-tooltip content="点击重新生成" placement="top" v-else-if="scope.row.qrState == 2">
              <el-button type="danger" size="small">生成失败</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="state">
          <template #default="scope">
            <dict-tag :options="module_state" :value="scope.row.state" />
          </template>
        </el-table-column>
        <el-table-column label="本月账单日" align="center" prop="beginDate"/>
        <el-table-column label="本月还款日" align="center" prop="endDate"/>
        <el-table-column label="添加时间" align="center" prop="createTime" width="160"/>
        <el-table-column label="账单模式" align="center" prop="billType">
          <template #default="scope">
            <dict-tag :options="bill_type" :value="scope.row.billType" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="220">
          <template #default="scope">
            <el-tooltip content="本月账单" placement="top">
              <router-link :to="'/bill/out/record?rId=' + scope.row.id" v-hasPermi="['credit:monthRecord:list']" style="margin-right: 10px;">
                <el-button link type="primary" icon="Document"></el-button>
              </router-link>
            </el-tooltip>
            <el-tooltip content="账单生成" placement="top">
              <el-button link type="primary" icon="Promotion" @click="handleSplitBill(scope.row)" v-hasPermi="['credit:monthRecord:split']"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['credit:monthRecord:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['credit:monthRecord:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"/>
    </el-card>

    <!-- 添加或修改信用卡还款的月份标识记录对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="billMonthRecordFormRef" :model="form" :rules="rules" label-width="140px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="本卡账单日">
              <el-input v-model="form.creditCard.statementDay" placeholder="请输入账单日" readonly style="width: 80%">
                <template #prepend>每月</template>
                <template #append>日</template>
              </el-input>
            </el-form-item>
            <el-form-item label="本卡还款日">
              <el-input v-model="form.creditCard.repaymentDay" placeholder="请输入还款日" readonly style="width: 80%">
                <template #prepend>每月</template>
                <template #append>日</template>
              </el-input>
            </el-form-item>
            <el-form-item label="本卡总额度">
              <el-input v-model="form.creditCard.totalLimit" readonly style="width: 80%">
                <template #append>元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="本卡剩余额度">
              <el-input v-model="form.creditCard.leftLimit" readonly style="width: 80%">
                <template #append>元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="本卡临时额度">
              <el-input v-model="form.creditCard.tempLimit" readonly style="width: 80%">
                <template #append>元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="本卡刷卡费率">
              <el-input v-model="form.creditCard.posRate" readonly style="width: 80%">
                <template #append>%</template>
              </el-input>
            </el-form-item>
            <el-form-item label="本卡扫码费率">
              <el-input v-model="form.creditCard.qrRate" readonly style="width: 80%">
                <template #append>%</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">

            <el-form-item label="本次拆分月份" prop="monthCode">
              <el-date-picker clearable v-model="form.monthCode" type="month"
                              value-format="YYYY-MM" placeholder="请选择卡片有效期">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="本月账单日" prop="beginDate">
              <el-date-picker clearable v-model="form.beginDate" type="date"
                              value-format="YYYY-MM-DD" placeholder="请选择账单日">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="本月还款日" prop="endDate">
              <el-date-picker clearable v-model="form.endDate" type="date"
                              value-format="YYYY-MM-DD" placeholder="请选择还款日">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="本期拆分金额" prop="billTotalMoney">
              <el-input v-model="form.billTotalMoney" placeholder="请输入本期拆分金额" type="number" style="width: 80%">
                <template #append>元</template>
              </el-input>
            </el-form-item>


            <el-form-item label="是否已缴纳管理费" prop="isPayFee">
              <el-radio-group v-model="form.isPayFee">
                <el-radio :label="0" :value="0">未缴纳</el-radio>
                <el-radio :label="1" :value="1">已缴纳</el-radio>
              </el-radio-group>
            </el-form-item>


            <el-form-item label="管理费金额" prop="payFee" v-if="form.isPayFee == 1">
              <el-input v-model="form.payFee" placeholder="请输入本期管理费" type="number" style="width: 80%">
                <template #append>元</template>
              </el-input>
            </el-form-item>

            <el-form-item label="状态" prop="state">
              <el-radio-group v-model="form.state">
                <el-radio v-for="dict in module_state" :key="parseInt(dict.value)" :label="parseInt(dict.value)">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="账单类型" prop="billType">
              <el-radio-group v-model="form.billType">
                <el-radio v-for="dict in bill_type" :key="parseInt(dict.value)" :label="parseInt(dict.value)">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BillMonthRecord" lang="ts">
import {
  listBillMonthRecord,
  getBillMonthRecord,
  delBillMonthRecord,
  addBillMonthRecord,
  updateBillMonthRecord,
  splitBillRecord
} from '@/api/credit/bill/record';
import { BillMonthRecordVO, BillMonthRecordQuery, BillMonthRecordForm } from '@/api/credit/bill/record/types';

import {getCard} from "@/api/credit/card";
//新页面接收参数js
import { useRoute } from "vue-router"
//注意是useRoute
const route = useRoute()
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { module_state } = toRefs<any>(proxy?.useDict('module_state'));
const { bill_type } = toRefs<any>(proxy?.useDict('bill_type'));



const billMonthRecordList = ref<BillMonthRecordVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);


// const creditCard = ref<CardVO>();

const queryFormRef = ref<ElFormInstance>();
const billMonthRecordFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: BillMonthRecordForm = {
  id: undefined,
  tenantId: undefined,
  creditCardId: undefined,
  monthCode: undefined,
  /**
   * 开始日期
   */
  beginDate: undefined,

  /**
   * 结束日期
   */
  endDate: undefined,
  billTotalMoney:undefined,
  state: undefined,
  createTime: undefined,
  billType: undefined,
  creditCard: {},
}
const data = reactive<PageData<BillMonthRecordForm, BillMonthRecordQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    creditCardId: undefined,
    monthCode: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    creditCardId: [
      { required: true, message: "信用卡id不能为空", trigger: "blur" }
    ],
    monthCode: [
      { required: true, message: "月份不能为空", trigger: "blur" }
    ],
    beginDate: [
      { required: true, message: "账单日不能为空", trigger: "blur" }
    ],
    endDate: [
      { required: true, message: "还款日不能为空", trigger: "blur" }
    ],
    billTotalMoney: [
      { required: true, message: "本期拆分金额不能为空", trigger: "blur" }
    ],
    isPayFee: [
      { required: true, message: "请选择是否已缴纳管理费", trigger: "blur" }
    ],
    payFee: [
      { required: true, message: "请输入管理费", trigger: "blur" }
    ],
    state: [
      { required: true, message: "请选择状态", trigger: "blur" }
    ],
    billType: [
      { required: true, message: "请选择账单模式", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询信用卡还款的月份标识记录列表 */
const getList = async () => {
  loading.value = true;
  const res = await listBillMonthRecord(queryParams.value);
  billMonthRecordList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}


const getCardDetail = async(id:number)=>{
  const res = await getCard(id);
  console.log('getCardDetail',res.data)
  Object.assign(form.value.creditCard, res.data);
}


function back() {
  if (proxy?.$route.query.noGoBack) {
    proxy.$router.push({ path: "/" });
  } else {
    proxy?.$router.go(-1);
  }
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  billMonthRecordFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: BillMonthRecordVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加信用卡还款的月份标识记录";
  if(queryParams.value.creditCardId!=undefined) {
    getCardDetail(queryParams.value.creditCardId)
  }
}

/** 修改按钮操作 */
const handleUpdate = async (row?: BillMonthRecordVO) => {
  reset();

  const _id = row?.id || ids.value[0]
  const res = await getBillMonthRecord(_id);
  Object.assign(form.value, res.data);
  if(queryParams.value.creditCardId!=undefined){
    getCardDetail(queryParams.value.creditCardId)
  }
  dialog.visible = true;
  dialog.title = "修改信用卡还款的月份标识记录";
}

/** 提交按钮 */
const submitForm = () => {
  billMonthRecordFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.creditCardId = queryParams.value.creditCardId;
      if (form.value.id) {
        await updateBillMonthRecord(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addBillMonthRecord(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}



/** 删除按钮操作 */
const handleDelete = async (row?: BillMonthRecordVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除信用卡还款的月份标识记录编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delBillMonthRecord(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}


/** 生成本月账单 */
const handleSplitBill = async (row?: BillMonthRecordVO) => {
  const _id = row?.id || ids.value[0]
  await proxy?.$modal.confirm('是否确认生成本月账单？').finally(() => loading.value = false);
  await splitBillRecord(_id);
  proxy?.$modal.msgSuccess("生成成功");
  await getList();
}




/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('credit/billMonthRecord/export', {
    ...queryParams.value
  }, `billMonthRecord_${new Date().getTime()}.xlsx`)
}

onMounted(() => {

  console.log('接收参数 ', route.query.agentId)//输出的即为接收到的参数
  if(route.query.cId != undefined){
    queryParams.value.creditCardId = parseInt(route.query.cId as string);
    form.value.creditCardId = parseInt( route.query.cId as string);
  }

  getList();
});
</script>
